import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
var _excluded = ["urls"],
    _excluded2 = ["urls"],
    _excluded3 = ["urls"],
    _excluded4 = ["bucketName", "attachmentUUID", "urls"];

/**
 * 文件相关
 * @creationDate 2019/12/25
 */
import request from "../../utils/request";
import { getIeVersion } from "../../utils/browser";
import { getEnvConfig } from "../../utils/iocUtils";
import { filterNullValueObject, getAccessToken, getCurrentOrganizationId, getResponse, isTenantRoleLevel } from "../../utils/utils";

var _getEnvConfig = getEnvConfig(),
    API_HOST = _getEnvConfig.API_HOST,
    CPAAS_FILE = _getEnvConfig.CPAAS_FILE;
/**
 * 获取fileList
 * {CPAAS_FILE}/v1/files/{attachmentUUID}/file
 * todo {CPAAS_FILE}/v1/{organizationId}/files/{attachmentUUID}/file
 * @export
 * @param {object} params 传递参数
 * @param {string} params.attachmentUUID - 文件uuid
 */


export function queryFileList(_x) {
  return _queryFileList.apply(this, arguments);
}
/**
 * 获取fileList(租户级)
 * {CPAAS_FILE}/v1/{organizationId}/files/{attachmentUUID}/file
 * @export
 * @param {object} params 传递参数
 * @param {string} params.attachmentUUID - 文件uuid
 */

function _queryFileList() {
  _queryFileList = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(params) {
    var tenantId;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            tenantId = getCurrentOrganizationId();
            return _context.abrupt("return", request("".concat(CPAAS_FILE, "/v1").concat(isTenantRoleLevel() ? "/".concat(tenantId, "/") : '/', "files/").concat(params.attachmentUUID, "/file"), {
              method: 'GET',
              query: params
            }));

          case 2:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _queryFileList.apply(this, arguments);
}

export function queryFileListOrg(_x2) {
  return _queryFileListOrg.apply(this, arguments);
}
/**
 * 删除文件
 * {CPAAS_FILE}/v1/files/delete-by-uuidurl/not-null
 * @export
 * @param {object} params 传递参数
 * @param {string} params.bucketName - 桶
 * @param {string} params.attachmentUUID - 文件uuid
 * @param {string} params.storageCode - 存储配置编码
 * @param {string[]} params.urls - 删除文件
 */

function _queryFileListOrg() {
  _queryFileListOrg = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(params) {
    var organizationId;
    return _regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            organizationId = getCurrentOrganizationId();
            return _context2.abrupt("return", request("".concat(CPAAS_FILE, "/v1/").concat(organizationId, "/files/").concat(params.attachmentUUID, "/file"), {
              method: 'GET',
              query: params
            }));

          case 2:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));
  return _queryFileListOrg.apply(this, arguments);
}

export function removeFileList(_x3) {
  return _removeFileList.apply(this, arguments);
}
/**
 * 删除上传的文件
 * {CPAAS_FILE}/v1/files/delete-by-url
 * {CPAAS_FILE}/v1/{organizationId}/files/delete-by-url
 * @param {object} params
 * @param {string} params.bucketName
 * @param {string} params.storageCode - 存储配置编码
 */

function _removeFileList() {
  _removeFileList = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(params) {
    var urls, otherParams, reqUrl;
    return _regeneratorRuntime.wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            urls = params.urls, otherParams = _objectWithoutProperties(params, _excluded);
            reqUrl = "".concat(CPAAS_FILE, "/v1/files/delete-by-uuidurl/not-null");
            return _context3.abrupt("return", request(reqUrl, {
              method: 'POST',
              body: params.urls,
              query: filterNullValueObject(otherParams)
            }));

          case 3:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  }));
  return _removeFileList.apply(this, arguments);
}

export function removeUploadFile(_x4) {
  return _removeUploadFile.apply(this, arguments);
}
/**
 * 删除attachmentUUID对应的某一个文件
 * {CPAAS_FILE}/v1/files/delete-by-uuidurl
 * todo {CPAAS_FILE}/v1/{organizationId}/files/delete-by-uuidurl
 * @export
 * @param {object} params 传递参数
 * @param {string} params.bucketName - 桶
 * @param {string} params.attachmentUUID - 文件uuid
 * @param {string[]} params.urls - 要删除的文件
 */

function _removeUploadFile() {
  _removeUploadFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(params) {
    var urls, otherParams, tenantId, reqUrl;
    return _regeneratorRuntime.wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            urls = params.urls, otherParams = _objectWithoutProperties(params, _excluded2);
            tenantId = getCurrentOrganizationId();
            reqUrl = isTenantRoleLevel() ? "".concat(CPAAS_FILE, "/v1/").concat(tenantId, "/files/delete-by-url") : "".concat(CPAAS_FILE, "/v1/files/delete-by-url");
            return _context4.abrupt("return", request(reqUrl, {
              method: 'POST',
              body: urls,
              query: filterNullValueObject(otherParams)
            }));

          case 4:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4);
  }));
  return _removeUploadFile.apply(this, arguments);
}

export function removeFile(_x5) {
  return _removeFile.apply(this, arguments);
}
/**
 * 删除attachmentUUID对应的某一个文件(租户级)
 * {CPAAS_FILE}/v1/{organizationId}/files/delete-by-uuidurl
 * @export
 * @param {object} params 传递参数
 * @param {string[]} params.urls - 删除的文件
 * @param {string} params.bucketName - 桶
 * @param {string} params.attachmentUUID - 文件uuid
 */

function _removeFile() {
  _removeFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(params) {
    var urls, otherParams, tenantId, reqUrl;
    return _regeneratorRuntime.wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            urls = params.urls, otherParams = _objectWithoutProperties(params, _excluded3);
            tenantId = getCurrentOrganizationId();
            reqUrl = isTenantRoleLevel() ? "".concat(CPAAS_FILE, "/v1/").concat(tenantId, "/files/delete-by-uuidurl") : "".concat(CPAAS_FILE, "/v1/files/delete-by-uuidurl");
            return _context5.abrupt("return", request(reqUrl, {
              method: 'POST',
              body: urls,
              query: filterNullValueObject(otherParams)
            }));

          case 4:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5);
  }));
  return _removeFile.apply(this, arguments);
}

export function removeFileOrg(_x6) {
  return _removeFileOrg.apply(this, arguments);
}
/**
 * 获取fileList
 * {CPAAS_FILE}/v1/files/uuid
 * {CPAAS_FILE}/v1/{organizationId}/files/uuid
 * @export
 * @param {object} params 传递参数
 */

function _removeFileOrg() {
  _removeFileOrg = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(params) {
    var organizationId, bucketName, attachmentUUID, urls, otherParams;
    return _regeneratorRuntime.wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            organizationId = getCurrentOrganizationId();
            bucketName = params.bucketName, attachmentUUID = params.attachmentUUID, urls = params.urls, otherParams = _objectWithoutProperties(params, _excluded4);
            return _context6.abrupt("return", request("".concat(CPAAS_FILE, "/v1/").concat(organizationId, "/files/delete-by-uuidurl"), {
              method: 'POST',
              query: _objectSpread({
                bucketName: bucketName,
                attachmentUUID: attachmentUUID
              }, filterNullValueObject(otherParams)),
              body: urls
            }));

          case 3:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee6);
  }));
  return _removeFileOrg.apply(this, arguments);
}

export function queryUUID(_x7) {
  return _queryUUID.apply(this, arguments);
}
/**
 * 获取导出Excel的列数据
 * @export
 * @param {object} params 传递参数
 */

function _queryUUID() {
  _queryUUID = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(params) {
    var tenantId;
    return _regeneratorRuntime.wrap(function _callee7$(_context7) {
      while (1) {
        switch (_context7.prev = _context7.next) {
          case 0:
            tenantId = getCurrentOrganizationId();
            return _context7.abrupt("return", request("".concat(CPAAS_FILE, "/v1").concat(isTenantRoleLevel() ? "/".concat(tenantId, "/") : '/', "files/uuid"), {
              method: 'POST',
              query: params
            }));

          case 2:
          case "end":
            return _context7.stop();
        }
      }
    }, _callee7);
  }));
  return _queryUUID.apply(this, arguments);
}

export function queryColumn(_x8) {
  return _queryColumn.apply(this, arguments);
}

function _queryColumn() {
  _queryColumn = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(params) {
    return _regeneratorRuntime.wrap(function _callee8$(_context8) {
      while (1) {
        switch (_context8.prev = _context8.next) {
          case 0:
            return _context8.abrupt("return", request("".concat(params.requestUrl), {
              method: params.method,
              query: {
                exportType: 'COLUMN'
              }
            }));

          case 1:
          case "end":
            return _context8.stop();
        }
      }
    }, _callee8);
  }));
  return _queryColumn.apply(this, arguments);
}

/**
 * 下载
 * @export
 * @param {object} params 传递参数
 * @param {string} params.requestUrl 下载文件请求的url
 * @param {array} params.queryParams 下载文件请求的查询参数，参数格式为：[{ name: '', value: '' }]]
 */
export function downloadFile(_x9) {
  return _downloadFile.apply(this, arguments);
}
/**
 * initiateAsyncExport 发起异步导出请求
 * @param {string} params - 参数
 */

function _downloadFile() {
  _downloadFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(params) {
    var _ref, url, queryParams, method, newUrl, iframeName, iframe, downloadForm, tokenInput;

    return _regeneratorRuntime.wrap(function _callee9$(_context9) {
      while (1) {
        switch (_context9.prev = _context9.next) {
          case 0:
            _ref = params || {}, url = _ref.requestUrl, queryParams = _ref.queryParams, method = _ref.method;
            newUrl = !url.startsWith('/api') && !url.startsWith('http') ? "".concat(API_HOST).concat(url) : url;
            iframeName = "".concat(url).concat(Math.random()); // 构建iframe

            iframe = document.createElement('iframe');
            iframe.setAttribute('name', iframeName);
            iframe.setAttribute('id', iframeName);
            iframe.style.width = '0px';
            iframe.style.height = '0px';
            iframe.style.display = 'none'; // 构建form

            downloadForm = document.createElement('form');

            if (getIeVersion() === -1) {
              // 如果当前浏览器不为ie
              // form 指向 iframe
              downloadForm.setAttribute('target', iframeName);
            } // 设置token


            tokenInput = document.createElement('input');
            tokenInput.setAttribute('type', 'hidden');
            tokenInput.setAttribute('name', 'access_token');
            tokenInput.setAttribute('value', "".concat(getAccessToken())); // 处理post请求时token效验

            if (method === 'POST') {
              newUrl = "".concat(newUrl, "?access_token=").concat(getAccessToken());
            } // 表单添加请求配置


            downloadForm.setAttribute('method', method);
            downloadForm.setAttribute('action', newUrl);
            downloadForm.appendChild(tokenInput); // 表单添加查询参数

            if (queryParams && Array.isArray(queryParams)) {
              queryParams.forEach(function (item) {
                var input = document.createElement('input');
                input.setAttribute('type', 'hidden');
                input.setAttribute('name', item.name);
                input.setAttribute('value', item.value);
                downloadForm.appendChild(input);
              });
            }

            document.body.appendChild(iframe);
            document.body.appendChild(downloadForm);
            downloadForm.submit(); // setTimeout(() => {
            //   document.body.removeChild(downloadForm);
            //   document.body.removeChild(iframe);
            // }, 2500);

            return _context9.abrupt("return", true);

          case 24:
          case "end":
            return _context9.stop();
        }
      }
    }, _callee9);
  }));
  return _downloadFile.apply(this, arguments);
}

export function initiateAsyncExport(_x10) {
  return _initiateAsyncExport.apply(this, arguments);
}

function _initiateAsyncExport() {
  _initiateAsyncExport = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(params) {
    var url, queryParams, newUrl, res;
    return _regeneratorRuntime.wrap(function _callee10$(_context10) {
      while (1) {
        switch (_context10.prev = _context10.next) {
          case 0:
            url = params.requestUrl, queryParams = params.queryParams;
            newUrl = !url.startsWith('/api') && !url.startsWith('http') ? "".concat(API_HOST).concat(url) : url;

            if (queryParams && Object.keys(queryParams).length >= 1) {
              queryParams.forEach(function (item) {
                newUrl += "".concat(newUrl.indexOf('?') >= 0 ? '&' : '?').concat(item.name, "=").concat(item.value);
              });
            }

            res = request(newUrl, {
              method: 'GET'
            }); // FIXME: @WJC utils need fix
            // @ts-ignore

            return _context10.abrupt("return", getResponse(res));

          case 5:
          case "end":
            return _context10.stop();
        }
      }
    }, _callee10);
  }));
  return _initiateAsyncExport.apply(this, arguments);
}